#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
排列5序列LSTM增强模式完整演示
展示排列5专用的真实训练模型预测功能
"""

import sys
import os
from PyQt5.QtWidgets import QApplication

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

def demo_plw_sequence_lstm():
    """完整演示排列5序列LSTM功能"""
    print("🎯 排列5序列LSTM增强模式完整演示")
    print("=" * 80)
    
    try:
        from lottery_predictor_app import LotteryPredictorApp
        
        # 创建应用
        if not QApplication.instance():
            app = QApplication(sys.argv)
        
        predictor = LotteryPredictorApp()
        
        print("📋 功能特点:")
        print("  ✅ 专门为排列5设计的序列LSTM模型")
        print("  ✅ 位置感知：每个位置（万位、千位、百位、十位、个位）独立预测")
        print("  ✅ 允许重复：严格遵循排列5规则（0-9数字可重复）")
        print("  ✅ 真实训练：基于历史数据训练的深度学习模型")
        print("  ✅ 智能备选：模型不可用时自动使用确定性算法")
        
        print("\\n🧪 算法对比测试:")
        print("-" * 60)
        
        # 测试所有算法对排列5的支持
        algorithms = [
            ("🤖 LSTM-CRF 经典模式", "lstm_crf"),
            ("🔥 序列LSTM 增强模式", "enhanced_lstm"),
            ("🚀 梯度提升 奇偶平衡", "gradient_boost"),
            (" 模式记忆 网络预测", "memory_network"),
            ("⚖️ 权重专家 系统预测", "weighted_expert")
        ]
        
        for name, method in algorithms:
            print(f"\\n{name}:")
            try:
                if method == "lstm_crf":
                    predictions = predictor.get_lstm_crf_predictions("plw", 2)
                elif method == "enhanced_lstm":
                    predictions = predictor.get_enhanced_lstm_predictions("plw", 2)
                elif method == "gradient_boost":
                    predictions = predictor.get_gradient_boost_predictions("plw", 2)
                elif method == "memory_network":
                    predictions = predictor.get_memory_network_predictions("plw", 2)
                elif method == "weighted_expert":
                    predictions = predictor.get_weighted_expert_predictions("plw", 2)
                
                for i, pred in enumerate(predictions):
                    numbers = pred['red']
                    confidence = pred.get('confidence', 'N/A')
                    print(f"  第{i+1}组: {numbers} (置信度: {confidence})")
                
                # 验证排列5规则
                valid = True
                for pred in predictions:
                    if len(pred['red']) != 5:
                        valid = False
                        print(f"  ❌ 错误：数字数量不是5个")
                        break
                    if len(pred['blue']) != 0:
                        valid = False
                        print(f"  ❌ 错误：排列5不应有蓝球")
                        break
                    for num in pred['red']:
                        if not (0 <= num <= 9):
                            valid = False
                            print(f"  ❌ 错误：数字{num}超出排列5范围(0-9)")
                            break
                
                if valid:
                    print("  ✅ 排列5规则验证通过")
                    
            except Exception as e:
                print(f"  ❌ 预测失败: {e}")
        
        print("\\n🔍 序列LSTM增强模式详细分析:")
        print("-" * 60)
        
        # 详细分析序列LSTM预测
        enhanced_predictions = predictor.get_enhanced_lstm_predictions("plw", 5)
        
        print(f" 生成预测数量: {len(enhanced_predictions)}")
        
        # 统计分析
        all_numbers = []
        for pred in enhanced_predictions:
            all_numbers.extend(pred['red'])
        
        print(f" 数字统计分析:")
        for digit in range(10):
            count = all_numbers.count(digit)
            percentage = count / len(all_numbers) * 100
            print(f"  数字{digit}: 出现{count}次 ({percentage:.1f}%)")
        
        print(f"\\n📊 位置分析:")
        for pos in range(5):
            position_names = ["万位", "千位", "百位", "十位", "个位"]
            pos_numbers = [pred['red'][pos] for pred in enhanced_predictions]
            unique_numbers = set(pos_numbers)
            print(f"  {position_names[pos]}: {pos_numbers} (不重复数字: {len(unique_numbers)}个)")
        
        print("\\n✨ 排列5序列LSTM特色功能:")
        print("  🎯 位置感知预测：每个位置都有专门的预测网络")
        print("  🔄 允许数字重复：符合排列5真实规则")
        print("  📈 序列学习：从历史开奖序列中学习模式")
        print("   注意力机制：关注重要的历史信息")
        print("  ⚡ 双向LSTM：同时考虑前后时间关系")
        
        return True
        
    except Exception as e:
        print(f" 演示失败: {e}")
        import traceback
        print(traceback.format_exc())
        return False

def demo_model_comparison():
    """演示模型对比"""
    print("\\n🆚 模型对比演示:")
    print("=" * 80)
    
    try:
        from lottery_predictor_app import LotteryPredictorApp
        from PyQt5.QtWidgets import QApplication
        
        if not QApplication.instance():
            app = QApplication(sys.argv)
        
        predictor = LotteryPredictorApp()
        
        print("🔬 同一输入的不同算法预测结果:")
        
        # 获取相同数量的预测进行对比
        algorithms = [
            ("LSTM-CRF", "lstm_crf"),
            ("序列LSTM", "enhanced_lstm"),
            ("梯度提升", "gradient_boost"),
            ("模式记忆", "memory_network"),
            ("权重专家", "weighted_expert")
        ]
        
        all_predictions = {}
        for name, method in algorithms:
            try:
                if method == "lstm_crf":
                    preds = predictor.get_lstm_crf_predictions("plw", 3)
                elif method == "enhanced_lstm":
                    preds = predictor.get_enhanced_lstm_predictions("plw", 3)
                elif method == "gradient_boost":
                    preds = predictor.get_gradient_boost_predictions("plw", 3)
                elif method == "memory_network":
                    preds = predictor.get_memory_network_predictions("plw", 3)
                elif method == "weighted_expert":
                    preds = predictor.get_weighted_expert_predictions("plw", 3)
                
                all_predictions[name] = preds
                print(f"✅ {name}: 成功生成{len(preds)}组预测")
                
            except Exception as e:
                print(f" {name}: 预测失败 - {e}")
        
        # 对比分析
        print("\\n📊 算法预测对比:")
        for i in range(3):
            print(f"\\n第{i+1}组预测:")
            for name, preds in all_predictions.items():
                if i < len(preds):
                    numbers = preds[i]['red']
                    print(f"  {name:8}: {numbers}")
        
        # 统计各算法的数字分布特点
        print("\\n📈 算法特点分析:")
        for name, preds in all_predictions.items():
            all_nums = []
            for pred in preds:
                all_nums.extend(pred['red'])
            
            avg_num = sum(all_nums) / len(all_nums)
            unique_count = len(set(all_nums))
            
            print(f"  {name:8}: 平均数字={avg_num:.1f}, 不重复数字={unique_count}个")
        
        return True
        
    except Exception as e:
        print(f" 对比演示失败: {e}")
        return False

if __name__ == "__main__":
    print("🚀 启动排列5序列LSTM增强模式演示")
    print("🎯 这是专门为排列5设计的深度学习预测模型")
    print()
    
    # 主演示
    demo_success = demo_plw_sequence_lstm()
    
    # 对比演示
    comparison_success = demo_model_comparison()
    
    print("\\n" + "=" * 80)
    print("🎉 演示总结:")
    print(f"  主要功能演示: {'✅ 成功' if demo_success else '❌ 失败'}")
    print(f"  算法对比演示: {'✅ 成功' if comparison_success else '❌ 失败'}")
    
    if demo_success and comparison_success:
        print("\\n🎯 排列5序列LSTM增强模式已成功集成!")
        print("🔥 现在可以在主程序中享受真实训练模型的预测能力!")
        print("\\n💡 主要特色:")
        print("  • 位置感知预测，每个位置独立建模")
        print("  • 允许数字重复，严格遵循排列5规则")
        print("  • 基于深度学习，从历史数据中学习模式")
        print("  • 智能备选机制，确保预测始终可用")
    else:
        print("\\n⚠️ 部分演示功能存在问题，建议进一步调试。")